package com.example.homework4.Model

class CardMatching(count: Int) {
    var score = 0
        private set

    private val cards: MutableList<Card>

    private val MISMATCH_PENALTY = 2
    private val MATCH_BONUS = 4
    private val COST_TO_CHOOSE = 1

    init {
        val deck = Deck()
        cards = mutableListOf()
        for (i in 0 until count) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }

    fun cardAtIndex(index: Int): Card {
        return cards[index]
    }

    fun chooseCardAtIndex(index: Int) {
        val card = cardAtIndex(index)
        if (!card.isMatched) {
            if (card.isChosen) {
                card.isChosen = false
            } else {
                val chosenCards = cards.filter { it.isChosen && !it.isMatched && it != card }

                if (chosenCards.isNotEmpty()) {
                    val otherCard = chosenCards[0]
                    val matchScore = card.match(arrayOf(otherCard))
                    if (matchScore > 0) {
                        score += matchScore * MATCH_BONUS
                        otherCard.isMatched = true
                        card.isMatched = true
                    } else {
                        score -= MISMATCH_PENALTY
                        otherCard.isChosen = false
                    }
                }
                score -= COST_TO_CHOOSE
                card.isChosen = true
            }
        }
    }
}